<?php

namespace App\Admin\Controllers;

use App\Models\User;
use function foo\func;
use Illuminate\Http\Request;
use App\Models\Department;
use Encore\Admin\Controllers\UserController as BaseController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class UserController extends BaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '用户管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $userModel = config('admin.database.users_model');
        $grid = new Grid(new $userModel());

        $grid->column('id', 'ID')->sortable();
        $grid->column('name', trans('admin.name'));
        $grid->column('department_id', '所属部门')->display(function ($department_id) {
            if ($department_id != 0) {
                return Department::find($department_id)->name;
            } else {
                return '';
            }
        });
        //$grid->column('roles', trans('admin.roles'))->pluck('name')->label();
        $grid->column('roles', trans('admin.roles'))->display(function () {
            $roles = $this->roles()->orderBy('type', 'desc')->get();
            $contentStr = '';
            $count = 0;
            foreach ($roles as $role) {
                if ($role->type == '系统类角色') {
                    $contentStr = $contentStr . '<span class="label label-warning" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                } else if ($role->type == '机构类角色') {
                    $contentStr = $contentStr . '<span class="label label-info" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                } else {
                    $contentStr = $contentStr . '<span class="label label-success" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                }
                $count++;
                if ($count > 3) {
                    $contentStr = $contentStr . '<br/>';
                    $count = 0;
                }
            }
            return $contentStr;
        });
        $grid->column('is_enable', '启用')->using([
            true => '正常',
            false => '禁用',
        ], '未知')->label([
            true => 'success',
            false => 'warning',
        ], 'warning');

        $grid->column('created_at', trans('admin.created_at'));

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            if ($actions->getKey() == 1) {
                $actions->disableDelete();
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });

        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->disableIdFilter();
                $filter->equal('department_id', '所属部门')->select('/admin/portrait/departments/getDepartment');
                $filter->equal('name', '员工名称');
            });
            $filter->column(1 / 2, function ($filter) {
//                $filter->where(function ($query) {
//                    $query->whereHas('roles', function ($query) {
//                        $query->where('address', 'like', "%{$this->input}%")->orWhere('email', 'like', "%{$this->input}%");
//                    });
//                }, '用户角色');
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('username', __('Username'));
        $show->field('name', __('Name'));
        $show->field('email', __('Email'));
        $show->field('emp_number', __('Emp number'));
        $show->field('id_number', __('Id number'));
        $show->field('phone', __('Phone'));
        $show->field('password', __('Password'));
        $show->field('avatar', __('Avatar'));
        $show->field('email_verified_at', __('Email verified at'));
        $show->field('remember_token', __('Remember token'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('admin.database.users_model');
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $userModel());

        $userTable = config('admin.database.users_table');
        $connection = config('admin.database.connection');

        $form->display('id', 'ID');
//        $form->text('username', trans('admin.username'))
//            ->creationRules(['required', "unique:{$connection}.{$userTable}"])
//            ->updateRules(['required', "unique:{$connection}.{$userTable},username,{{id}}"]);
        $form->text('name', trans('admin.name'))->rules('required');
        //员工编号
        $form->text('id_number', trans('admin.id_number'))
            ->creationRules(["unique:{$connection}.{$userTable}"])
            ->updateRules(["unique:{$connection}.{$userTable},emp_number,{{id}}"]);
        //员工编号
        $form->text('emp_number', trans('admin.emp_number'))
            ->creationRules(["unique:{$connection}.{$userTable}"])
            ->updateRules(["unique:{$connection}.{$userTable},emp_number,{{id}}"]);
        //电话号码
        $form->text('phone', trans('admin.phone'))
            ->creationRules(["unique:{$connection}.{$userTable}"])
            ->updateRules(["unique:{$connection}.{$userTable},phone,{{id}}"]);
//        //邮箱
//        $form->text('email', trans('admin.email'))
//            ->creationRules(['required', "unique:{$connection}.{$userTable}"])
//            ->updateRules(['required', "unique:{$connection}.{$userTable},email,{{id}}"]);
        $form->image('avatar', trans('admin.avatar'));
        $form->password('password', trans('admin.password'))->rules('required|confirmed');
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });

        $form->ignore(['password_confirmation']);

        $form->select('department_id', '部门名称')->options(Department::selectOptions());

        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));
        $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

        //$form->display('created_at', trans('admin.created_at'));
        //$form->display('updated_at', trans('admin.updated_at'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        return $form;
    }
}
